package v1

import (
	"net/http"
	"rustdesk_api_server/api/request"
	"rustdesk_api_server/api/response"
	"rustdesk_api_server/api/services"

	"github.com/gin-gonic/gin"
)

type AuthApi struct{}

func (api *AuthApi) Login(ctx *gin.Context) {
	var form request.LoginForm
	if err := ctx.ShouldBindJSON(&form); err != nil {
		ctx.JSON(http.StatusOK, response.JsonResult{
			Error: err.Error(),
		})
		ctx.Abort()
		return
	}

	token, err := services.Auth.UserLogin(form.Username, form.Password, form.ClientId, form.UUID, ctx.ClientIP())
	if err != nil {
		ctx.JSON(http.StatusOK, response.JsonResult{
			Code:  -1,
			Error: err.Error(),
		})
		return
	}

	if err != nil {
		ctx.JSON(http.StatusOK, response.JsonResult{
			Code:  -1,
			Error: err.Error(),
		})
	}

	ctx.JSON(http.StatusOK, gin.H{
		"access_token": token,
		"user": gin.H{
			"name": form.Username,
		},
	})
}

func (api *AuthApi) Logout(ctx *gin.Context) {
	var form request.LogoutForm
	err := ctx.ShouldBindJSON(&form)
	if err != nil {
		ctx.JSON(http.StatusOK, response.JsonResult{
			Code:  -1,
			Error: err.Error(),
		})
	}

	ctx.JSON(http.StatusOK, gin.H{"data": "success"})
}
